import React, {PureComponent} from "react"
import "./receiver-selector.less"
import "animate.css"
import {compose, lifecycle, withHandlers, withState} from "recompose"
import {del, get, postJSON, putJSON} from "../../../shared/server"
import { Icon as LegacyIcon } from '@ant-design/compatible';
import { Radio, Popconfirm } from "antd";
import {Button} from "antd"
import ReceiverForm from "./form"
import cs from "classnames"


class ReceiverSelector extends PureComponent {

  render() {
    const {
      data,
      modalVisible,
      $modalVisible,
      handleSubmit,
      formTitle,
      initData,
      toAppend,
      toEdit,
      toDelete,
      selectedId,
      onSelectReceiver,
    } = this.props
    return (
      <div className={'receiver-selector'}>
        <h4>选择收货人</h4>
        <Radio.Group>
          {
            data && data.length > 0
              ? data.map((r, idx) =>
                <ReceiverSelectorOption
                  onEdit={toEdit}
                  onDelete={toDelete}
                  key={idx}
                  onSelect={onSelectReceiver}
                  selectedId={selectedId}
                  data={r}/>)
              : undefined
          }
        </Radio.Group>
        <div className={'btn-bar'}>
          <Button type={'primary'} onClick={toAppend} ghost>
            <LegacyIcon type={'plus'}/> 添加收件人
          </Button>
        </div>

        <ReceiverForm visible={modalVisible}
                      title={formTitle}
                      initData={initData}
                      onCancel={() => $modalVisible(false)}
                      onOk={handleSubmit}/>
      </div>
    );
  }
}


class ReceiverSelectorOption extends PureComponent {
  render() {
    const {data, onEdit, onDelete, selectedId, onSelect} = this.props
    const addr = `${data.province} ${data.city} ${data.county} ${data.address}`
    return (
      <div className={cs('receiver-selector-opt', {'selected': data.id === selectedId})}>
        <Radio value={data.id} checked={data.id === selectedId} onClick={onSelect(data)}>
          <span className={'receiver-name'}>{data['receiverName']}</span>
        </Radio>
        <div>{data['receiverPhone']}</div>
        <div className={'addr'}>{addr}</div>
        <Button onClick={onEdit(data)} type={'link'}>编辑</Button>
        <Popconfirm
          title={`确定要删除收件人 [${data.receiverName}] 吗?`}
          onConfirm={onDelete(data)}
          okText="确定"
          cancelText="取消"
        >
          <Button type={'link'}>删除</Button>
        </Popconfirm>

      </div>

    )
  }
}

const appendTitle = <div><LegacyIcon type={'plus'}/> 新建收件人</div>
const editTitle = <div><LegacyIcon type={'edit'}/> 编辑收件人</div>

const receiverSelectorCompose = compose(
  withState('data', '$data', []),
  withState('initData', '$initData', {}),
  withState('modalVisible', '$modalVisible', false),
  withState('formTitle', '$formTitle', appendTitle),
  withState('selectedId', '$selectedId', null),
  withHandlers({
    getData: ({$data}) => {
      return () => {
        get(`/receiver`).then(d => $data(d))
      }
    }
  }),
  withHandlers({
      submitForm: ({getData, $modalVisible, initData}) => {
        return (formData, successCallback) => {
          const submitData = {
            ...formData
          }
          submitData.province = formData.area[0]
          submitData.city = formData.area[1]
          submitData.county = formData.area[2]
          if (initData.id) {
            putJSON(`/receiver/${initData.id}`, submitData)
              .then(d => {
                if (d) {
                  $modalVisible(false)
                  successCallback()
                  getData()
                }
              })
            return
          }
          postJSON(`/receiver`, submitData)
            .then(d => {
              if (d) {
                $modalVisible(false)
                successCallback()
                getData()
              }
            })
        }
      },
      toAppend: ({$initData, $modalVisible, $formTitle}) => {
        return () => {
          $initData({})
          $formTitle(appendTitle)
          $modalVisible(true)
        }
      },
      toEdit: ({$initData, $modalVisible, $formTitle}) => {
        return (data) => () => {
          $initData(data)
          $formTitle(editTitle)
          $modalVisible(true)
        }
      },
      toDelete: ({getData}) => {
        return (data) => () => {
          del(`/receiver/${data.id}`).then(d => {
            if (d) {
              getData()
            }
          })
        }
      },
      onSelectReceiver: ({onSelect, $selectedId}) => {
        return (data) => () => {
          $selectedId(data.id)
          if (onSelect) onSelect(data)
        }
      }
    }
  ),
  withHandlers({
    handleSubmit: ({submitForm}) => {
      return (form) => {
        form.validateFields((err, values) => {
          if (err) {
            return
          }
          submitForm(values, () => form.resetFields())
        })
      }
    }
  }),
  lifecycle({
    componentDidMount() {
      const {getData} = this.props
      getData()
    }
  })
)

export default receiverSelectorCompose(ReceiverSelector)